<?php
namespace Home\Controller;
use Think\Controller;
class WeixinController extends Controller {
    public function index(){
    	$redirect_uri = urlencode('http://'.$_SERVER['SERVER_NAME'].U('home/weixin/callback'));
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect ";
        redirect($url);
    }
    public function callback(){
    	$code = $_GET['code'];
    	$log_access_token_api = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.APPID.'&secret='.APPSECRET.'&code='.$code.'&grant_type=authorization_code ';
    	$log_access_token_data = json_decode(http_get($log_access_token_api));
    	var_dump($log_access_token_data->openid).'<br/>';
    	$user_info_api = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$log_access_token_data->access_token.'&openid='.$log_access_token_data->openid.'&lang=zh_CN';
    	$user_info = json_decode(http_get($user_info_api),true);//json_decode还是对象，加true可以使其转换为数组
    		
    	if(!M('user')->where(array('openid'=>$log_access_token_data->openid))->find()){
	    	M('user')->add(array(
	    		'nickname'=>$user_info['nickname'],
	    		'sex'=>$user_info['sex'],
	    		'city'=>$user_info['city'],
	    		'province'=>$user_info['province'],
	    		'country'=>$user_info['country'],
	    		'headimgurl'=>$user_info['headimgurl'],
	    		'openid'=>$log_access_token_data->openid
	    		));
    	}
		$this->assign('user_info',$user_info);
		$this->display();
    }
  
}